﻿using System;
using System.Web.Mvc;

namespace Ioc.MvcApplication.Controllers
{
    public class HomeController : Controller
    {
        public HomeController(ISomeAwesomeService someAwesomeService, IAnotherService anotherService)
        {
            _someAwesomeService = someAwesomeService;
            _anotherService = anotherService;
        }

        private readonly ISomeAwesomeService _someAwesomeService;
        private readonly IAnotherService _anotherService;

        public ActionResult Index()
        {
            return Content(string.Format("{0} {1}", _someAwesomeService, _anotherService));
        }
    }

    public interface ISomeAwesomeService
    {
    }
    public interface IAnotherService
    {
    }
    public interface IRepository
    {
    }

    public class SomeAwesomeService : ISomeAwesomeService
    {
        public SomeAwesomeService(IRepository repository)
        {
            _repository = repository;
        }

        private readonly IRepository _repository;
        private readonly int _id = IdGenerator.NextId();

        public override string ToString()
        {
            return "SomeAwesomeService " + _id + "<br />" + _repository;
        }
    }
    public class AnotherService : IAnotherService
    {
        public AnotherService(IRepository repository)
        {
            _repository = repository;
        }

        private readonly IRepository _repository;
        private readonly int _id = IdGenerator.NextId();

        public override string ToString()
        {
            return "AnotherService " + _id + "<br />" + _repository;
        }
    }
    public class Repository : IRepository
    {
        private readonly int _id = IdGenerator.NextId();

        public override string ToString()
        {
            return "--- Repository " + _id + "<br />";
        }
    }

    public static class IdGenerator
    {
        private static readonly object _lock = new object();
        private static int _lastId;

        public static int NextId()
        {
            lock (_lock)
                return _lastId++;
        }
    }
}